package com.ictech.print.service;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;


import com.ictech.print.protocal.ProtocolPrinter;
import com.ictech.print.utils.PreferencesUtil;

import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;

/**
 * 项目名称：print
 * 创建人：bear
 * 创建时间：2018/12/24
 */

public class PrinterService extends Service {
    private static String TAG = "PrinterService";

    private final static String ServiceUUID = "00001101-0000-1000-8000-00805F9B34FB";   //SPP服务UUID号

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mPrinter = null;     //蓝牙设备
    private BluetoothSocket mSocket = null;      //蓝牙通信socket
    private InputStream mBis = null;              //蓝牙输入流

    public final static String ACTION_PRINTER_SERVICE_STOP =
            "com.bear.ms.ACTION_PRINTER_SERVICE_STOP";
    public final static String ACTION_PRINTER_SERVICE_CONNECT =
            "com.bear.ms.ACTION_PRINTER_SERVICE_CONNECT";
    public final static String ACTION_PRINTER_SOCKER_ERROR =
            "com.bear.ms.ACTION_PRINTER_SOCKER_ERROR";

    private String printerMac;     //打印机地址

    private ProtocolPrinter mProtocol;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate方法");
        mProtocol = new ProtocolPrinter(new int[]{});
        printerMac = PreferencesUtil.get("printerMac");
        if (printerMac.equals("")) {
            printerMac = "00:00:00:00:00:00";
        }
        Thread ConnectThread = new Thread(new Runnable() {
            @Override
            public void run() {
                if (!ConnectPrinter())  {            //连接socket为耗时操作，要写在线程中。
                    broadcastUpdate(ACTION_PRINTER_SOCKER_ERROR);
                }else {
                    Log.i(TAG, "连接成功");
                    broadcastUpdate(ACTION_PRINTER_SERVICE_CONNECT);
                }
            }
        });
        ConnectThread.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand方法");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy方法");
        if (ReadDataThread.isAlive()){
            ReadDataThread.interrupt();
        }
        CloseSocket();
        broadcastUpdate(ACTION_PRINTER_SERVICE_STOP);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(TAG, "onRebind方法");
        super.onRebind(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind方法");
        return new MethodAgent();
    }

    /**
     * 连接蓝牙打印机
     * @return      是否连接成功
     */
    private boolean ConnectPrinter(){
        final BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager == null){
            return false;
        }
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        mPrinter = mBluetoothAdapter.getRemoteDevice(printerMac);
        if (mPrinter != null){
            // 用服务号得到socket
            try{
                mSocket = mPrinter.createRfcommSocketToServiceRecord(UUID.fromString(ServiceUUID));
            }catch(IOException e){
                Log.i(TAG, "fault to get socket");
                e.printStackTrace();
                return false;
            }
            try {
                mSocket.connect();
            } catch (IOException e) {
                Log.i(TAG,"fault ro connect socket");
                e.printStackTrace();
                CloseSocket();
                return false;
            }
        }

        //开启一个线程来读取输入流
        try {
            mBis = mSocket.getInputStream();
            if (!ReadDataThread.isAlive()){
                ReadDataThread.start();
            }
        }catch (Exception e){
            Log.i(TAG, "fault to get inputstream");
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 输出数据到蓝牙打印机
     * @param data     需要输出的数据
     * @return          是否输出成功
     */
    private boolean WriteData(byte[] data){
        if (mSocket == null){
            return false;
        }
        try{
            OutputStream mBos = mSocket.getOutputStream();   //蓝牙连接输出流
            mBos.write(data);
        }catch(IOException e){
            Log.i(TAG, "输出异常");
            return false;
        }
        return true;
    }

    Thread ReadDataThread = new Thread(new Runnable() {
        @Override
        public void run() {
            boolean flag = true;
            int len = 0;
            while (flag){
                try {
                    len = mBis.available();
                    if (len>0){
                        int[] mData = new int[len];
                        for (int i=0; i<len; i++){
                            mData[i] = mBis.read();
                        }
                        mProtocol.ReadData(mData);
                    }
                } catch (IOException e) {
                    flag = false;
                    e.printStackTrace();
                }
            }
        }
    });

    private void CloseSocket(){
        if (mSocket != null){
            try {
                Log.i(TAG, "socket已关闭");
                mSocket.close();
                mSocket = null;
            } catch (IOException e) {
                Log.i(TAG,"fault ro close socket");
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送自定义广播，告知广播接受者蓝牙状态的改变
     * @param action
     */
    private void broadcastUpdate(final String action) {
        final Intent intent = new Intent(action);
        sendBroadcast(intent);
    }

    /**
     * 给绑定该服务的对象提供本服务的方法
     */
    public class MethodAgent extends Binder {
        public ProtocolPrinter getProtocal() {
            return mProtocol;
        }

        public boolean printMyQRCode(int size, String content, int align){
            return WriteData(mProtocol.printMyQRCode(size, content, align));
        }

        public boolean printMyBarCode(String content, int widthByte, int heightByte, int align, boolean hir){
            return WriteData(mProtocol.printMyBarCode(content, widthByte, heightByte, align, hir));
        }

        public boolean printMyCode128(String content, int align) {
            return WriteData(mProtocol.printMyCode128(content, align));
        }

        public boolean printBill(String content) {
            byte[] printData = mProtocol.printBill(content);
            if (printData != null) {
                return WriteData(printData);
            }else {
                return false;
            }
        }
    }

}
